﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Rison.BusinessFacade.Common;
using Rison.DataAccess.Data.NRBZ;
using Rison.DataAccess.Common;
using Rison.BusinessFacade.Helper;
using Rison.BusinessFacade.Entity.NRBZ;
using System.Diagnostics;


namespace Rison.BusinessFacade.Facade.NRBZ 
{
   public sealed class NrbzFacade : FacadeBase
    {
        protected override DataAccessBase dbObject
        {
            get
            {
                if (dbHelper == null)
                    dbHelper = new NrbzDb();

                return dbHelper;
            }
        }

        protected override string identityFieldName
        {
            get { return "ID"; }
        }

        protected override List<SqlField> GetSqlFieldCollection(object value, bool getIdentityField)
        {
            List<SqlField> fields = new List<SqlField>();
            if (getIdentityField)
                fields.Add(new SqlField("ID", (value as NrbzEntity).ID, true, false));
            else
                fields.Add(new SqlField("ID", (value as NrbzEntity).ID));

            fields.Add(new SqlField("DepartID", (value as NrbzEntity).DepartID));
            fields.Add(new SqlField("Year", (value as NrbzEntity).Year));
            fields.Add(new SqlField("IfZwxw", (value as NrbzEntity).IfZwxw));
            fields.Add(new SqlField("Xwfbzq", (value as NrbzEntity).Xwfbzq));
            fields.Add(new SqlField("IfTpxw", (value as NrbzEntity).IfTpxw));
            fields.Add(new SqlField("Bssl", (value as NrbzEntity).Bssl));
            fields.Add(new SqlField("txtLevel", (value as NrbzEntity).txtLevel));
            fields.Add(new SqlField("ifCharacterProj", (value as NrbzEntity).ifCharacterProj));
            fields.Add(new SqlField("characterProjName", (value as NrbzEntity).characterProjName));
            fields.Add(new SqlField("characterProjUrl", (value as NrbzEntity).characterProjUrl));
            fields.Add(new SqlField("CreateTime", (value as NrbzEntity).CreateTime));
            fields.Add(new SqlField("Creator", (value as NrbzEntity).Creator));
            fields.Add(new SqlField("LastModifiedTime", (value as NrbzEntity).LastModifiedTime));
            fields.Add(new SqlField("LastModified", (value as NrbzEntity).LastModified));
            fields.Add(new SqlField("State", (value as NrbzEntity).State));
            fields.Add(new SqlField("FieldTotal", (value as NrbzEntity).FieldTotal));
            fields.Add(new SqlField("FieldNum", (value as NrbzEntity).FieldNum));


            return fields;
        }

        protected override object SetPropertiesValue(DataRow row)
        {
            NrbzEntity obj = new NrbzEntity();

            obj.ID = StringHelper.GetValue(row, "ID");
            obj.DepartID = StringHelper.GetValue(row, "DepartID");
            obj.Year = StringHelper.GetValue(row, "Year");
            obj.IfZwxw = StringHelper.GetValue(row, "IfZwxw");
            obj.Xwfbzq = StringHelper.GetValue(row, "Xwfbzq");
            obj.IfTpxw = StringHelper.GetValue(row, "IfTpxw");
            obj.Bssl = StringHelper.GetValue(row, "Bssl");
            obj.txtLevel = StringHelper.GetValue(row, "txtLevel");

            obj.gwxxNum = StringHelper.GetValue(row, "gwxxNum");
            obj.zfxxNum = StringHelper.GetValue(row, "zfxxNum");
            obj.gkjNum = StringHelper.GetValue(row, "gkjNum");
            obj.lmzfxx = StringHelper.GetValue(row, "lmzfxx");
            obj.Ifbmgkml = StringHelper.GetValue(row, "Ifbmgkml");
            obj.Ifxsqsydw = StringHelper.GetValue(row, "Ifxsqsydw");
            obj.Ifqyly = StringHelper.GetValue(row, "Ifqyly");
            obj.Ifqygkml = StringHelper.GetValue(row, "Ifqygkml");
            obj.FieldTotal = Convert.ToInt32(row["FieldTotal"]);
            obj.FieldNum = Convert.ToInt32(row["FieldNum"]);
            obj.CreateTime = StringHelper.GetValue(row, "CreateTime");
            obj.Creator = StringHelper.GetValue(row, "Creator");
            obj.LastModifiedTime = StringHelper.GetValue(row, "LastModifiedTime");
            obj.LastModified = StringHelper.GetValue(row, "LastModified");
            obj.State = StringHelper.GetValue(row, "State");


            return obj;
        }

        public DataRow GetInformation(string departid, string year)
        {
            DataRow dr = (dbObject as NrbzDb).GetInformation(departid, year);
            return dr;
        }

       //是否填报
        public string isExistSelfExam(string departid, string year)
        {
            DataRow dr = GetInformation(departid, year);
            if (dr != null)
            {
                if (dr["state"].ToString() == "1")
                {
                    return "已提交";
                }
                return "填报中";
            }

            return "未填报";
        }

        //完成率
        public int getWCL(string departid, string year)
        {
            try
            {
                DataRow dr = GetInformation(departid, year);
                if (dr != null)
                {
                    return Convert.ToInt16(dr["FieldNum"].ToString()) * 100 / Convert.ToInt16(dr["FieldTotal"].ToString());
                }
            }
            catch
            {
            }

            return 0;
        }

        public int updateValue(List<DataField> l,string id)
        {
            StringBuilder SqlString = new StringBuilder();

            for(int i=0; i<l.Count;i++)
            {
                DataField f = l[i];
                if (i == l.Count - 1)
                {
                    SqlString.AppendFormat("{0}='{1}'", f.Name, f.Value);
                }
                else
                {
                    SqlString.AppendFormat("{0}='{1}',", f.Name, f.Value);
                }
            }

           int returnVal=(dbObject as NrbzDb).UpdateValue(SqlString.ToString(),id);

           return returnVal;

        }

        #region "处理子网站"
        public DataTable LoadSubInfobyParentId(string parentId,string type,int fieldNum)
        {
            if (parentId == "")
                return null;

            DataSet ds = (dbObject as NrbzDb).GetSubInfoByParentID(parentId,type);

            if (ds == null)
                return null;

            DataTable tempTable = new DataTable();
            DataColumn dc=new DataColumn();

            for (int i=0;i<fieldNum;i++)
            {
                dc = new DataColumn();
                tempTable.Columns.Add(dc);
            }
            dc = new DataColumn("ifShow");
            tempTable.Columns.Add(dc);

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                string var1 = dr["var1"].ToString();
                string[] s = var1.Split(',');
                int rowcount = s.Length / fieldNum;

                for(int m=0; m<rowcount;m++)
                {
                    DataRow datarow = tempTable.NewRow();
                    for (int j = 0; j < fieldNum; j++)
                    {
                        datarow[j] = s[m * fieldNum + j].ToString();
                    }
                    datarow["ifShow"] = dr["ifShow"].ToString();
                    tempTable.Rows.Add(datarow);
                }

                
            }

            return tempTable;

        }
        #endregion

        public string SaveSubInfobyParentId(string parentId, string type,int fieldNum,string param)
        {
            if (parentId == "")
                return "";
            
            int returnValue = -1;

            try
            {
                returnValue = DeleteSubInfobyParentId(parentId,type);

                returnValue = InsertSubInfobyParentId(parentId,type,fieldNum,param);
            }

            catch
            {

            }

            if (returnValue < 0)
                return "更新子表出错！";

            return "";
        }

        public int DeleteSubInfobyParentId(string parentId,string type)
        {
            if (parentId != "")
            {
                return (dbObject as NrbzDb).DeleteSubInfobyParentId(parentId,type);
            }
            return 0;
        }

        public int InsertSubInfobyParentId(string parentId, string type, int fieldNum, string con)
        {
            int returnValue = 0;
            string[] arr = con.Split(',');
            int remainder = arr.Length % fieldNum;
            Debug.Assert(remainder == 0);
            for (int i = 0; i < arr.Length; i ++ )
            {
                if (i % fieldNum == 0)
                {
                    con = "";
                }
                else
                {
                    con += ",";
                }

                if (arr[i].Length > 300)
                {
                    con += arr[i].Substring(0,300);
                }
                else
                {
                    con += arr[i];
                }

                if (i % fieldNum == fieldNum - 1)
                {
                    StringBuilder param = new StringBuilder();
                    StringBuilder field = new StringBuilder();

                    field.AppendFormat("{0},{1},{2},{3}", "id", "examid", "type", "var1");

                    param.Append("newid()");
                    param.Append(",'" + parentId + "'");
                    param.Append(",'" + type + "'");
                    param.Append(",'" + con + "'");
                    (dbObject as NrbzDb).InsertSubInfobyParentId(field.ToString(), param.ToString());
                }

                
            }


             return returnValue;
            
            

        }

        public int GetSubInfoCountbyShow(string parentid, string type, int fieldNum)
        {
            if (parentid != "")
            {
                DataSet ds = (dbObject as NrbzDb).GetSubInfoCountbyShow(parentid, type);
                int num = 0;
                if (ds != null)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                         num = num + Convert.ToInt16(dr[0].ToString().Split(',').Length) / fieldNum;
                    }                  
                    return num;
                }
            }
            return 0;
        }

        //public int InsertSubInfobyParentId(string parentId,string type,int fieldNum,string con)
        //{
        //    if (con != null && con != "")
        //    {
        //        int returnValue = -1;
        //        string[] a = con.Split(',');
        //        int rowCount = a.Length / fieldNum;

        //        for (int i = 0; i < rowCount; i++)
        //        {
        //            StringBuilder param = new StringBuilder();
        //            StringBuilder field = new StringBuilder();

        //            param.Append("newid()");
        //            param.Append(",'" + parentId + "'");
        //            param.Append(",'" + type + "'");
        //            param.Append(",'" + (i + 1).ToString() + "'");

        //            for (int j = 0; j < fieldNum; j++)
        //            {
        //                param.Append(",'" + a[i * fieldNum + j].ToString() + "'");
        //            }
                    
        //            //param.Append("'" + a[i * fieldNum + 1].ToString() + "',");


        //            returnValue = (dbObject as NrbzDb).InsertSubInfobyParentId(param.ToString());
        //        }
        //        return returnValue;
        //    }
        //    return 0;

        //}

        public int InsertAttachment(string parentid,int type,List<SysAttachment> attachments)
        {
            StringBuilder sql = new StringBuilder();
            int reVal = 0;
            foreach (SysAttachment a in attachments)
            {
                sql = new StringBuilder();
                sql.Append("insert into UploadFile (ID,ExamID,PhysicalName,DisplayName,FileSize,UploadTime,Type) values ");
                sql.AppendFormat("('{0}','{1}','{2}','{3}','{4}',getdate(),'{5}')", Guid.NewGuid().ToString(), parentid, a.FilePath, a.FileName, a.FileSize,type);

                reVal = (dbObject as NrbzDb).SaveAttachment(sql.ToString());

               
            }

            return reVal;
        }

        public int DeleteAttachment(string ids)
        {
            StringBuilder sql = new StringBuilder();
            int reVal = 0;
            if (ids != "0")
            {
                string[] id = ids.Split(',');
                sql.Append("delete from UploadFile where id in (");
                for (int i = 0; i < id.Length; i++)
                {
                    if (i != id.Length - 1)
                    {
                        sql.AppendFormat("'{0}',", id[i].ToString());
                    }
                    else
                    {
                        sql.AppendFormat("'{0}')", id[i].ToString());
                    }
                    
                }
                reVal = (dbObject as NrbzDb).DeleteAttachment(sql.ToString());

            }

            return reVal;
        }

       public DataSet LoadAttachement(string parentid,int type)
       {
           StringBuilder sql = new StringBuilder();
            
            sql = new StringBuilder();
            sql.Append("select * from UploadFile where ");
            sql.AppendFormat("examid='{0}' and type ='{1}'", parentid,type);

            return (dbObject as NrbzDb).LoadAttachement(sql.ToString());

       }

      
    }
}
